package com.zxhysy.log.annotation.advisor;

import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.StaticMethodMatcherPointcut;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * 日志切点
 * @author zhangxinhong
 * @since 2021/9/23 14:58
 */
public class LogSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 日志数据源
     */
    private final LogSource logSource;

    public LogSourcePointcut(LogSource logSource) {
        this.logSource = logSource;
        setClassFilter(new LogOperationSourceClassFilter());
    }

    /**
     * 需匹配的类
     * @param method      方法
     * @param targetClass 目标类
     * @return 是否需要过滤
     * @see LogOperationSourceClassFilter
     * 再判断是否可以类上有没有注解或者方法上有没有注解
     */
    @Override
    public boolean matches(Method method, Class<?> targetClass) {
        return !logSource.getLogOperations(method, targetClass).isEmpty();
    }

    /**
     * 类过滤器
     */
    private class LogOperationSourceClassFilter implements ClassFilter {
        /**
         * 指定资源包
         * @param clazz 类
         * @return 是否过滤
         */
        @Override
        public boolean matches(Class<?> clazz) {
            return logSource.isCandidateClass(clazz);
        }
    }

}
